<template>
  <!-- 分享链接 -->
  <div>
    <!-- 头部按钮 -->
    <div class="create_box">
      <el-button type="primary" :disabled="judgePermission('share')" @click="createEnjoyLinkClick">新增分享</el-button>
    </div>

    <!-- 表格数据 -->
    <div class="table_box">
      <el-table :data="EnjoyHistory" v-loading="historyLoading" style="width: 100%">
        <el-table-column prop="createTime" label="分享时间"></el-table-column>
        <el-table-column prop="password" label="密码"></el-table-column>

        <el-table-column prop="deadline" label="有效时间">
          <template #default="scope">
            <span>{{ scope.row.deadline ? scope.row.deadline : '永久' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="access" label="访问权限">
          <template #default="scope">
            <span>{{ scope.row.isPreview == 1 ? '预览' : '' }}</span>
            <span>{{ scope.row.isPreview == 1 && scope.row.isDownload == 1 ? '/' : '' }}</span>
            <span>{{ scope.row.isDownload == 1 ? '下载' : '' }}</span>
          </template>
        </el-table-column>

        <el-table-column width="100">
          <template #default="scope">
            <div style="display: flex; justify-content: space-around">
              <el-tooltip class="operate_tooltip" effect="dark" content="复制" placement="top-start">
                <span @click="copyLink(scope.row.linkAddress)">
                  <el-icon class="icon_class"><CopyDocument /></el-icon>
                </span>
              </el-tooltip>
              <el-tooltip class="operate_tooltip" effect="dark" content="编辑" placement="top-start">
                <span @click="editHistoryLink(scope.row.id)">
                  <el-icon class="icon_class"><EditPen /></el-icon>
                </span>
              </el-tooltip>
              <el-tooltip class="operate_tooltip" effect="dark" content="删除" placement="top-start">
                <span @click="apiFilesShareDelete(scope.row.id)">
                  <el-icon class="icon_class"><Close /></el-icon>
                </span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="block">
      <el-pagination
        @current-change="handleCurrentChange"
        v-model:current-page.sync="currentPage.page"
        v-model:page-size="currentPage.size"
        layout="total, prev, pager, next"
        :total="currentPage.total"
      >
      </el-pagination>
    </div>

    <!-- 分享弹框 -->
    <el-dialog
      title="链接分享"
      v-model="dialogEnjoy"
      width="550px"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="closeDialogEnjoyClick"
    >
      <div v-if="isEnjoySuccess">
        <el-form :model="formEnjoy">
          <div style="display: flex; flex-direction: column">
            <el-form-item v-if="formEnjoy.shareForm == '1'" label="设置密码" label-width="80px">
              <div class="input-password">
                <el-input v-model="formEnjoy.password" placeholder="请输入密码" />
                <el-tooltip effect="dark" :content="tooltipPassword" placement="top">
                  <el-icon style="margin-left: 15px; font-size: 19px"><Warning /></el-icon>
                </el-tooltip>
              </div>
            </el-form-item>

            <el-form-item label="过期时间:" label-width="80px">
              <div style="display: flex; justify-content: space-between; width: 100%">
                <el-date-picker
                  v-model="formEnjoy.deadline"
                  type="datetime"
                  placeholder="选择日期时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  @input="$forceUpdate()"
                >
                </el-date-picker>
                <div class="more_set" @click="isMoreSetDiv = !isMoreSetDiv">
                  <span>更多设置</span>
                  <el-icon v-if="isMoreSetDiv"><CaretTop /></el-icon>
                  <el-icon v-else><CaretBottom /></el-icon>
                </div>
              </div>
            </el-form-item>

            <!-- 更多设置 -->
            <div class="" v-if="isMoreSetDiv">
              <el-form-item label="操作权限:" label-width="80px">
                <div style="display: flex; align-items: center">
                  <el-checkbox-group v-model="formEnjoy.isPreview"><el-checkbox label="预览" disabled></el-checkbox></el-checkbox-group>
                  <el-checkbox-group v-model="formEnjoy.isDownload" style="margin-left: 15px">
                    <el-checkbox label="下载"> </el-checkbox>
                  </el-checkbox-group>
                  <el-tooltip effect="dark" :content="tooltipContent" placement="top" style="margin-left: 15px">
                    <el-icon style="margin-left: 15px; font-size: 19px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
              </el-form-item>

              <el-form-item label="可访问者:" label-width="80px" v-if="!isTeamPeople">
                <el-tag
                  :key="indext"
                  v-for="(tag, indext) in formEnjoy.accessibleArray"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag)"
                >
                  {{ tag.userName ? tag.userName : tag.name }}
                </el-tag>
                <el-button class="button-new-tag" type="primary" @click="showInterviewDialogClick">选择可访问者</el-button>
              </el-form-item>
            </div>

            <el-form-item> </el-form-item>
          </div>
        </el-form>
        <!-- 弹窗底部操作按钮 -->
        <!-- <template #footer></template> -->
        <div class="dialog-footer" style="display: flex; justify-content: flex-end">
          <el-button @click="closeDialogEnjoyClick">取 消</el-button>
          <el-button type="primary" @click="SureDialogEnjoyClick">生成链接</el-button>
        </div>
      </div>

      <div v-if="!isEnjoySuccess">
        <div class="success_link">
          <span class="success_title">提取密码:</span>
          <span>{{ successLinkObj.shareForm == '1' ? successLinkObj.password : '无' }}</span>
        </div>
        <div class="success_link">
          <span class="success_title">过期时间:</span>
          <span>{{ successLinkObj.deadline ? successLinkObj.deadline : '永久' }}</span>
        </div>
        <div class="success_link">
          <span class="success_title">操作权限:</span>
          <span>{{ successLinkObj.isPreview == 1 ? '可预览' : '' }}</span>
          <span>{{ successLinkObj.isPreview == 1 && successLinkObj.isDownload == 1 ? '/' : '' }}</span>
          <span>{{ successLinkObj.isDownload == 1 ? '可下载' : '' }}</span>
        </div>
        <div class="success_link">
          <span class="success_title">链接地址:</span>
          <span class="success_url" @click="skipRedirectClick(successLinkObj.linkAddress)">{{ successLinkObj.linkAddress }}</span>
        </div>

        <div slot="footer" class="dialog-footer" style="display: flex; justify-content: flex-end">
          <el-button @click="editHistoryLink(successLinkObj.id)">编辑链接</el-button>
          <el-button type="primary" @click="copyLink(successLinkObj.linkAddress)">复制链接</el-button>
        </div>
      </div>
    </el-dialog>

    <SelectUser ref="SelectUserRef" @sureDialogTransferClick="sureDialogTransferClick" />
  </div>
</template>

<script setup lang="ts">
import { ApiPerfilesShare, ApiPerAddShare, ApiPerfilesShareId, ApiPerEditShare, ApiPerDeleteShare } from '@/api/personDoc/personDocApi';
import { randomPassword } from '@/utils/yuUtils.js';
import SelectUser from '@/views/components/select-user-check/select-user.vue'; // 选择人
import { useTeamRoleStore } from '@/store/modules/teamRole'
const SelectUserRef = ref(null);
import router from '@/router';
import useUserStore from '@/store/modules/user';
const teamRoleStore = useTeamRoleStore();
const userStore = useUserStore();
const { proxy } = getCurrentInstance() as any;
const emit: any = defineEmits(['enjoyListCurrentChange', 'createFilesShareLink', 'refreshEnjoyLinkClick']);
const historyLoading = ref(false);
const isMoreSetDiv = ref(false); //更多设置
const reg = /^(?:\d{4}|[A-Za-z]{4}|[A-Za-z\d]{4})$/;
const tooltipContent = ref(
  '请确认您拥有被分享文件的权限。例如，当您没有文件下载权限时将无法开启该文件外链的下载操作功能。如有需要请联系文件管理员获取文件权限。'
);
const DataInfo = ref([] as any);
const EnjoyHistory = ref([]);
const dialogEnjoy = ref(false);
const formEnjoy = reactive({
  shareForm: '1',
  password: '',
  deadline: '',
  isPreview: ['预览'],
  isDownload: ['下载'],
  visitsNumber: '',
  downloadsNumber: '',
  accessibleArray: [],
  remark: '',
  linkAddress: '',
  endTiem: '',
  id: '',
  name: ''
});
const infoId = ref('');

const infoData = ref({
  type: '',
  realName: '',
  id: ''
});
const successLinkObj: any = ref({
  shareForm: '1',
  password: '',
  deadline: '' as any,
  isPreview: ['预览'] as any,
  isDownload: ['下载'] as any,
  linkAddress: '',
  id: ''
});
const isEnjoySuccess = ref(true); //分享成功之后显示链接地址页面
const isCreateOrEdit = ref(null); //创建或者编辑链接  1为创建 2为编辑
const currentPage = reactive({
  page: 1,
  size: 10,
  total: 0
});
const isTeamPeople = ref('');
const tooltipPassword = ref('因为受法律限制，必须要设置密码才可以共享');

const props = defineProps({
  fileDetailInfo: {
    type: Object,
    default: () => {
      return {};
    }
  }
});

// 刷新共享链接
const refreshEnjoyLinkClick = () => {
  emit('refreshEnjoyLinkClick');
};

/**查询表格分享链接 */
const ShareFile = async (e: any) => {
  if (!e) {
    return;
  }

  // infoId.value = e.value.id;
  infoData.value = { ...e.value };
  historyLoading.value = true;
  let oParam = {
    fileId: props.fileDetailInfo.id,
    page: currentPage.page - 1,
    size: 10,
    type: 'team'
  };
  await ApiPerfilesShare(oParam).then((res) => {
    if (res.code == 200) {
      historyLoading.value = false;
      EnjoyHistory.value = res.data.rows;
      currentPage.total = res.data.total;
    }
  });
};

//创建链接
const createEnjoyLinkClick = () => {
  formEnjoy.shareForm = '1';
  formEnjoy.password = randomPassword(4); // 生成密码
  formEnjoy.deadline = '';
  formEnjoy.isPreview = ['预览'];
  formEnjoy.isDownload = ['下载'];
  formEnjoy.visitsNumber = '';
  formEnjoy.downloadsNumber = '';
  formEnjoy.accessibleArray = [];
  formEnjoy.remark = '';
  formEnjoy.linkAddress = '';
  formEnjoy.endTiem = '';
  isMoreSetDiv.value = false;
  dialogEnjoy.value = true;
  isEnjoySuccess.value = true;
  isCreateOrEdit.value = 1;
  isTeamPeople.value = '';
};

// 编辑历史链接
const editHistoryLink = (id) => {
  let oParam = {
    id: id
  };
  ApiPerfilesShareId(oParam).then((res) => {
    let val: any = res;
    formEnjoy.shareForm = val.shareForm.toString();
    formEnjoy.password = val.password; // 生成密码
    // formEnjoy.deadline = new Date(val.deadline) || (formEnjoy.deadline as any);
    formEnjoy.deadline = val.deadline || (formEnjoy.deadline as any);
    formEnjoy.isPreview = val.isPreview == 1 ? ['预览'] : [];
    formEnjoy.isDownload = val.isDownload == 1 ? ['下载'] : [];
    formEnjoy.visitsNumber = val.visitsNumber != undefined ? val.visitsNumber : '';
    formEnjoy.downloadsNumber = val.downloadsNumber != undefined ? val.downloadsNumber : '';
    formEnjoy.accessibleArray = val.users != undefined ? val.users : [];
    formEnjoy.remark = val.remark;
    formEnjoy.id = val.id;
    formEnjoy.name = val.name;

    isMoreSetDiv.value = false;
    isTeamPeople.value = val.teamType;
    dialogEnjoy.value = true;
    isEnjoySuccess.value = true;
    isCreateOrEdit.value = 2;
  });
};
// 删除链接
const apiFilesShareDelete = (id) => {
  let ids = [];
  ids.push(id);
  ApiPerDeleteShare(ids).then((res) => {
    ShareFile(props.fileDetailInfo.id);
    ElMessage.success('删除成功');
  });
};

// 复制链接
const copyLink = (val) => {
  // let urlArr = val.split('/')
  // let url = window.document.location.origin + '/enjoyLink?hash=' + urlArr[urlArr.length-1];
  let url = val;
  //新建一个文本框
  let oInput = document.createElement('input');
  //赋值给文本框
  oInput.value = url;
  document.body.appendChild(oInput);
  // 选择对象;
  oInput.select();
  // 执行浏览器复制命令
  document.execCommand('Copy');
  //复制完成删除掉输入框
  oInput.remove();
  ElMessage.success('复制成功');
};

// 重定向跳转到分享页面
const skipRedirectClick = (url) => {
  let urlArr = url.split('=');
  let hash = urlArr[urlArr.length - 1];
  let routerObj = {
    hash: hash
  };
  const { href } = router.resolve({
    path: '/enjoyLink',
    query: routerObj
  });

  window.open(href, '_blank');
};

const handleCurrentChange = (val) => {
  currentPage.page = val;
  // ShareFile(props.fileDetailInfo.id);
};

// 生成链接
const SureDialogEnjoyClick = () => {
  console.log(11111, isCreateOrEdit.value);
  // if (this.formEnjoy.deadline == '') {
  // 	this.$message.warning('过期时间不能为空');
  // 	return;
  // }

  // console.log(isCreateOrEdit.value, '创建还是编辑');

  if (formEnjoy.shareForm == '1' && !reg.test(formEnjoy.password)) {
    ElMessage.warning('密码不能为空,由数字或字母组成的4位密码');
    return;
  }

  if (formEnjoy.visitsNumber != '' && Number(formEnjoy.visitsNumber) <= 0) {
    ElMessage.warning('访问次数不能小于等于0,不填为无限次');
    return;
  }
  if (formEnjoy.visitsNumber != '' && Number(formEnjoy.downloadsNumber) <= 0) {
    ElMessage.warning('下载次数不能小于等于0,不填为无限次');
    return;
  }
  let accessibleId;
  // 没有选择必须时=是本团队的人
  if (!isTeamPeople.value) {
    accessibleId = formEnjoy.accessibleArray.map((item) => {
      return item.userId;
    });
  } else {
    accessibleId = formEnjoy.accessibleArray.map((item) => {
      return item.typeId;
    });
    accessibleId = [];
  }

  //创建链接
  if (isCreateOrEdit.value == 1) {
    //这里是创建链接的请求参数
    let requestData = {
      shareForm: parseInt(formEnjoy.shareForm),
      password: formEnjoy.shareForm == '1' ? formEnjoy.password : '',

      deadline: formEnjoy.deadline ? formEnjoy.deadline : '',
      isPreview: formEnjoy.isPreview.length != 0 ? 1 : 0,
      isDownload: formEnjoy.isDownload.length != 0 ? 1 : 0,
      visitsNumber: formEnjoy.visitsNumber ? parseInt(formEnjoy.visitsNumber) : '',
      downloadsNumber: formEnjoy.downloadsNumber ? parseInt(formEnjoy.downloadsNumber) : '',
      accessibleId: accessibleId.join(','), //选择人员id
      remark: formEnjoy.remark,
      linkAddress: window.document.location.origin, //地址传给后端
      status: 1,
      personId: userStore.userId,
      personName: userStore.nickname,
      fileId: props.fileDetailInfo.id || DataInfo.value.id, //文件id
      shareType: 'team',
      fileType: infoData.value.type || DataInfo.value.type,
      name: infoData.value.realName || DataInfo.value.realName,
      teamType: isCreateOrEdit.value
    };

    ApiPerAddShare(requestData).then((res) => {
      ShareFile(props.fileDetailInfo.id);
      proxy!.$forceUpdate();
      successLinkObj.value = res;
      isEnjoySuccess.value = false;
      ElMessage.success('创建成功');
    });

    // emit('createFilesShareLink', requestData, 1);
  }

  // 编辑链接
  if (isCreateOrEdit.value == 2) {
    //这里是编辑链接的请求参数
    let requestData = {
      shareForm: parseInt(formEnjoy.shareForm),
      password: formEnjoy.shareForm == '1' ? formEnjoy.password : '',
      deadline: formEnjoy.deadline ? formEnjoy.deadline : '',
      isPreview: formEnjoy.isPreview.length != 0 ? 1 : 0,
      isDownload: formEnjoy.isDownload.length != 0 ? 1 : 0,
      visitsNumber: formEnjoy.visitsNumber ? parseInt(formEnjoy.visitsNumber) : '',
      downloadsNumber: formEnjoy.downloadsNumber ? parseInt(formEnjoy.downloadsNumber) : '',
      accessibleId: accessibleId.join(','),
      remark: formEnjoy.remark,
      id: formEnjoy.id,
      name: formEnjoy.name,
      teamType: isCreateOrEdit.value
    };

    ApiPerEditShare(requestData).then((res) => {
      successLinkObj.value = res.data;
      ElMessage.success('编辑成功');
      isEnjoySuccess.value = false;
      ShareFile(props.fileDetailInfo.id);
    });
  }
};

//关闭共享
const closeDialogEnjoyClick = () => {
  dialogEnjoy.value = false;
};
// 叉掉访问者
const handleClose = (tag) => {
  formEnjoy.accessibleArray.splice(formEnjoy.accessibleArray.indexOf(tag), 1);
};

// 打开选择可访问者的dialog
const showInterviewDialogClick = () => {
  SelectUserRef.value.openDialogTransfer();

  // 如果选择了本团队的人
  //   if (isTeamPeople.value) {
  //     this.$refs.yuSelectUserNewUiRef.TeamPersonList = formEnjoy.accessibleArray;
  //     this.$refs.yuSelectUserNewUiRef.dialogTransfer = true;
  //   } else {
  //     this.$refs.yuDeptMember._data.TeamPersonList = formEnjoy.accessibleArray;
  //     this.$refs.yuDeptMember._data.dialogTransfer = true;
  //   }
};

//拿到选择的人
const sureDialogTransferClick = (val) => {
  formEnjoy.accessibleArray = val;
  SelectUserRef.value.closeDialogTransferClick();
};

/**权限控制 */
const judgePermission = (str) => {
  //   if (this.pageType == 'enterprise') {
  //     return !this.$yuUtils.documentsPermissionFunc([str], this.enterpriseMyRoleList);
  //   } else if (this.pageType == 'team') {
      
  //   } else {
  //     return false;
  //   }
  return !proxy.$yuUtils.documentsPermissionFunc([str], teamRoleStore.myTeamFileRoleList);
};

// 打开弹框
const openDialog = (val, num) => {
  isCreateOrEdit.value = num;
  DataInfo.value = val;
  console.log(DataInfo.value, 'DataInfo.value');
  dialogEnjoy.value = true;
  createEnjoyLinkClick();
};

defineExpose({
  SureDialogEnjoyClick,
  openDialog,
  ShareFile,
  refreshEnjoyLinkClick
});

onMounted(() => {
  // console.log(userStore, '333399999999999999999999999999');
});
</script>

<style lang="scss" scoped>
.table_box {
  :deep(th) {
    color: #666;
    font-weight: normal;
    font-size: 14px;
    height: 51px;
  }

  :deep(tr) {
    color: #333;
    height: 51px;
  }
}

.icon_class {
  font-size: 16px;
}

.icon_class:hover {
  cursor: pointer;
  color: #409eff;
}

.more_set {
  color: #409eff;
  font-size: 14px;
  margin-right: 40px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.success_link {
  margin-bottom: 8px;

  .success_title {
    margin-right: 5px;
  }
}

.success_url {
  color: #409eff;
}

.success_url:hover {
  cursor: pointer;
  border-bottom: 1px solid #409eff;
}

.create_box {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 6px;
  margin-right: 5px;
}

:deep(.el-button--text) {
  padding: 9px 15px;
  color: #aaa;
}

:deep(.el-button--text:hover) {
  color: #6698ff;
}

:deep(.el-button--primary) {
  background-color: #6698ff;
  border-color: #6698ff;
}

:deep(.el-button--primary:focus) {
  box-shadow: 0 2px 5px 1px rgba(102, 152, 255, 0.6);
}

:deep(.el-button--primary:hover) {
  box-shadow: 0 2px 5px 1px rgba(102, 152, 255, 0.6);
}

.el-button--primary.is-disabled {
  color: #fff !important;
  background-color: #94b7fd !important;
  border-color: #94b7fd !important;

  &:hover {
    box-shadow: none !important;
  }
}

.input-password {
  display: flex;
  align-items: center;
}
</style>
